package proxy;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Arrays;

import net.jxta.platform.NetworkManager;
import net.jxta.socket.JxtaMulticastSocket;

public class OverlayListener extends Thread {
	NetworkManager networkManager;
	JxtaMulticastSocket mcastSocket;
	 
	public OverlayListener(NetworkManager networkManager, JxtaMulticastSocket mcastSocket) {
		this.networkManager = networkManager;
		this.mcastSocket = mcastSocket;
	}

	public void run() {
//		try {
//			JxtaMulticastSocket  mcastSocket = new JxtaMulticastSocket(networkManager.getNetPeerGroup(), OverlayManager.getSocketAdvertisement());
		
        	while(true) {
        		try {
        			byte[] buffer = new byte[65535];
        	        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

		            // wait for a datagram. The following can be put into a loop
	        		mcastSocket.setSoTimeout(0);
		            mcastSocket.receive(packet);
		            String sw = new String(packet.getData(), 0, packet.getLength());
		            System.out.println("OverlayListener.java: Pacote recebido de :" + packet.getAddress());
		            System.out.println("OverlayListener.java: Meu endereço: " + mcastSocket.getLocalAddress());
		            System.out.println(sw);
		            
		            MulticastMessage message = parseMessage(packet.getData());
		            System.out.println("OverlayListener.java: Mensagem recebida: " + message);		            
		            
		            InetAddress ia = InetAddress.getByName(message.getIp());
					MulticastSocket ms = new MulticastSocket();
					ms.joinGroup(ia);

					DatagramPacket dp = new DatagramPacket(message.getMessage(), message.getMessage().length, ia, Integer.valueOf(message.getPort()));
					ms.setTimeToLive(5);
					System.out.println("OverlayListener.java: Enviando mensagem");										
					ms.send(dp);
					ms.leaveGroup(ia);
					ms.close();
        		} catch (Exception e) {
					e.printStackTrace();
				}
        	}		
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
	}
	
	private MulticastMessage parseMessage(byte[] data) {
		MulticastMessage message = new MulticastMessage();
//		Object pg;?
//		((PeerGroup)pg).getPipeService().
		int message_end = find_first(data, (byte)0) == 0 ? data.length : find_first(data, (byte)0); 		
		int start_trail = message_end - 25;
		System.out.println("OverlayListener.java: start_trail = " + start_trail);
		message.setMessage(Arrays.copyOf(data, data.length - start_trail));
		String trail = new String (Arrays.copyOfRange(data, start_trail, message_end));
		message.setIp(trail.substring(0, trail.indexOf(":")));
		message.setPort(trail.substring(trail.indexOf(":")+1, trail.indexOf(' ')));
		
		return message;
	}
		
	private int find_first(byte[] data, byte b) {
		for (int i = 0; i < data.length; i++) {
			if (data[i] == b)
				return i;
		}
		return 0;
	}

	class MulticastMessage {
		String ip;
		String port;
		byte[] message;
		
		public String getIp() {
			return ip;
		}
		public void setIp(String ip) {
			this.ip = ip;
		}
		public String getPort() {
			return port;
		}
		public void setPort(String port) {
			this.port = port;
		}
		public byte[] getMessage() {
			return message;
		}
		public void setMessage(byte[] message) {
			this.message = message;
		}
		
		public String toString() {
			return "ip =[" + ip + "] port =[" + port + "] message [=" + message + "]";
		}
	}
	
}
